package com.anti.modular.bus.hydropowermeter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.commom.core.utils.DecimalUtils;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.housebill.entity.HouseBill;
import com.anti.modular.bus.housebill.param.HouseBillParam;
import com.anti.modular.bus.housebill.service.HouseBillService;
import com.anti.modular.bus.housebilldetail.entity.HouseBillDetail;
import com.anti.modular.bus.housebilldetail.param.HouseBillDetailParam;
import com.anti.modular.bus.housebilldetail.result.HouseBillDetailResult;
import com.anti.modular.bus.housebilldetail.service.HouseBillDetailService;
import com.anti.modular.bus.houselease.entity.HouseLease;
import com.anti.modular.bus.houselease.param.HouseLeaseParam;
import com.anti.modular.bus.houselease.service.HouseLeaseService;
import com.anti.modular.bus.hydropowermeter.entity.HydropowerMeter;
import com.anti.modular.bus.hydropowermeter.enums.HydropowerMeterExceptionEnum;
import com.anti.modular.bus.hydropowermeter.param.HydropowerMeterParam;
import com.anti.modular.bus.hydropowermeter.result.HydropowerMeterResult;
import com.anti.modular.bus.hydropowermeter.service.HydropowerMeterService;
import com.anti.modular.bus.roomexpenses.entity.RoomExpenses;
import com.anti.modular.bus.roomexpenses.result.LeaseExpensesResult;
import com.anti.modular.bus.roomexpenses.result.RoomExpensesResult;
import com.anti.modular.bus.roomexpenses.service.LeaseExpensesService;
import com.anti.modular.bus.roomexpenses.service.RoomExpensesService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 水電抄表記錄表service接口实现类
 *
 * @author anti
 * @date 2021-05-10 21:19:36
 */
@Service
public class HydropowerMeterServiceImpl implements HydropowerMeterService {
    @Resource
    DBUtils dbUtils;
    @Resource
    HouseBillDetailService houseBillDetailService;
    @Resource
    LeaseExpensesService leaseExpensesService;
    @Resource
    RoomExpensesService roomExpensesService;
    @Resource
    HouseBillService houseBillService;
    @Override
    public HydropowerMeter getById(HydropowerMeterParam hydropowerMeterParam){
        String sql="select * from hydropower_meter where id =? ";
        return dbUtils.get(sql,HydropowerMeter.class,hydropowerMeterParam.getId());
    }

    @Override
    public PageResult page(PageParam pageParam,HydropowerMeterParam hydropowerMeterParam) {
        StringBuilder sb=new StringBuilder("select * from hydropower_meter where 1=1 and status =0 and meter_flag=1 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(hydropowerMeterParam)) {
            // 根据房間名稱 查询
            if (ObjectUtil.isNotEmpty(hydropowerMeterParam.getMeterReadingDate())) {
               sb.append(" and  DATE_FORMAT(meter_reading_date,'%Y-%m') = ?");
               param.add(hydropowerMeterParam.getMeterReadingDate());
            }
            // 根据租客 查询
            if (ObjectUtil.isNotEmpty(hydropowerMeterParam.getEstateId())&&hydropowerMeterParam.getEstateId()!=0) {
               sb.append(" and room_id in (select id from bus_room where estateid=? and status=0)");
               param.add(hydropowerMeterParam.getEstateId());
            }
            if (ObjectUtil.isNotEmpty(hydropowerMeterParam.getType())&&hydropowerMeterParam.getType()!=0) {
               sb.append(" and cost_id = ?");
               param.add(hydropowerMeterParam.getType());
            }
        }
        return dbUtils.query(pageParam,sb.toString(),param.toArray());
    }

    @Override
    public List<HydropowerMeter> list(HydropowerMeterParam hydropowerMeterParam) {
        String sql="";
        return dbUtils.query(sql,HydropowerMeter.class);
    }

    @Override
    public List<HydropowerMeter> getMeterListByBillId(Long leaseId,Long costId) {
        String sql="select * from hydropower_meter where status=0 and lease_id=? and cost_id=?";
        return dbUtils.query(sql,HydropowerMeter.class,leaseId,costId);
    }

    @Override
    public List<HydropowerMeterResult> getMeterListByStateIdOnJzcb(Long estateId, Long costId) {
        String sql="select a.*,c.rented_day as rented_days from hydropower_meter a,house_bill_detail b,house_bill c " +
                " where a.house_bill_detail_id=b.id and b.house_bill_id=c.id and c.bill_status in (0,3) " +
                " and b.status=0 and c.status=0 and a.status = 0 and a.room_id in  (select id from bus_room where estateid=? and status=0) and a.cost_id=?";
        List<HydropowerMeterResult> query = dbUtils.query(sql, HydropowerMeterResult.class, estateId, costId);
        return query;
    }

    @Override
    public HydropowerMeterResult getMeterListByStateIdOnJzcbForOne(Long leaseId,Long id) {
        String sql="select a.* from hydropower_meter a  RIGHT JOIN house_bill_detail b on a.house_bill_detail_id=b.id   RIGHT JOIN house_bill c\n" +
                "on b.house_bill_id = c.id where  a.house_bill_id=c.id  and b.status =0  and c.house_lease_id=? and a.cost_id=? and c.bill_status in (0,3)";
        HydropowerMeterResult query = dbUtils.get(sql, HydropowerMeterResult.class,leaseId,id);
        HouseBillParam houseBillParam=new HouseBillParam();
        houseBillParam.setId(query.getHouseBillId());
        HouseBill byId = houseBillService.getById(houseBillParam);
        query.setZdqs(byId.getQs());
        return query;
    }

    public List<HydropowerMeterResult> getLast(Long house_bill_id) {
        String sql="select * from hydropower_meter where status=0 and house_bill_id=?";
        return dbUtils.query(sql,HydropowerMeterResult.class,house_bill_id);
    }
    @Override
    public List<HydropowerMeterResult> getSdFyListByDetail(HydropowerMeterParam hydropowerMeterParam) {
        List<HydropowerMeterResult> hydropowerMeterResults = getLast(hydropowerMeterParam.getHouseBillId());
        List<Long> longList = hydropowerMeterResults.stream().map(it -> it.getHouseBillDetailId()).collect(Collectors.toList());
        List<LeaseExpensesResult> byIds=new ArrayList<>();
        if (longList.size()>0){
            byIds = leaseExpensesService.getByIds(longList);
        }
        for (int i = 0; i < byIds.size(); i++) {
            LeaseExpensesResult roomExpenses = byIds.get(i);
            for (int i1 = 0; i1 < hydropowerMeterResults.size(); i1++) {
                HydropowerMeterResult meterResult = hydropowerMeterResults.get(i1);
                if (roomExpenses.getHouseBillDetailId().equals(meterResult.getHouseBillDetailId())){
                    meterResult.setInitialreading(roomExpenses.getInitialreading());
                    meterResult.setAmountDu(roomExpenses.getAmount());
                    meterResult.setSolder(DecimalUtils.scale(roomExpenses.getSolder(),2));
                    break;
                }
            }
        }
        return hydropowerMeterResults;
    }

    @Override
    public BigDecimal preReading(Long leaseId,Long billId, Long costId) {
        String sql="select a.reading from hydropower_meter a where a.status=0 and a.lease_id=? and house_bill_id =? and cost_id=? order by house_bill_detail_id desc ";
        Double first = dbUtils.getFirst(sql, Double.class,leaseId,billId, costId);

        if (null==first){
            return new BigDecimal(0.00);
        }
        //BigDecimal
        return  DecimalUtils.toBigDecimal(first);
    }

    @Override
    public void add(HydropowerMeterParam hydropowerMeterParam) {
        HydropowerMeter hydropowerMeter = new HydropowerMeter();
        BeanUtil.copyProperties(hydropowerMeterParam, hydropowerMeter);
        hydropowerMeter.setCreateTime(new Date());
        hydropowerMeter.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.insert(hydropowerMeter);
    }

    @Override
    public void addJzcb(HydropowerMeterParam hydropowerMeterParam) {
        Long estateId = hydropowerMeterParam.getEstateId();
        String meterReadingDate = hydropowerMeterParam.getMeterReadingDate();
        DateTime parse = DateUtil.parse(meterReadingDate, "yyyy-MM-dd");
        List<HydropowerMeter> meterList = hydropowerMeterParam.getMeterList();
        String updateSql="update hydropower_meter set estate_id=?,reading=?,dosage=?,meter_reading_date=?,cost=?,meter_flag=?,update_time=?,update_user=?  where id =? ";
        HydropowerMeter hydropowerMeter =null;
        Date date = new Date();
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        for (int i = 0; i < meterList.size(); i++) {
            hydropowerMeter = meterList.get(i);
            Long id = hydropowerMeter.getId();
            BigDecimal reading = hydropowerMeter.getReading();
            BigDecimal dosage = hydropowerMeter.getDosage();
            BigDecimal cost = hydropowerMeter.getCost();
            dbUtils.execSql(updateSql,estateId,reading,dosage,parse,cost,1,date,sysLoginUserId,id);
        }
    }

    @Override
    public void addHuan(HydropowerMeterParam hydropowerMeterParam) {
        Long estateId = hydropowerMeterParam.getEstateId();
        BigDecimal read = BigDecimal.valueOf(0.00);
        List<HydropowerMeterResult> meterList = hydropowerMeterParam.getMeterResList();
        String updateSql="update hydropower_meter set estate_id=?,reading=?,dosage=?,pre_reading=?,cost=?,update_time=?,update_user=?  where id =? ";
        HydropowerMeterResult hydropowerMeter =null;
        Date date = new Date();
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        for (int i = 0; i < meterList.size(); i++) {
            hydropowerMeter = meterList.get(i);
            Long id = hydropowerMeter.getId();
            BigDecimal newCost = hydropowerMeter.getNewCost();
            dbUtils.execSql(updateSql,estateId,read,read,newCost,read,date,sysLoginUserId,id);
        }
    }

    @Override
    public void addHuanOne(HydropowerMeterResult hydropowerMeterParam) {
        String updateSql="update hydropower_meter set reading=?,dosage=?,pre_reading=?,cost=?,update_time=?,update_user=?  where id =? ";
        BigDecimal read = BigDecimal.valueOf(0.00);
        BigDecimal newCost = hydropowerMeterParam.getNewCost();
        Long id = hydropowerMeterParam.getId();
        dbUtils.execSql(updateSql,read,read,newCost,read,new Date(),LoginContextHolder.me().getSysLoginUserId(),id);
    }

    public void delete(HydropowerMeterParam hydropowerMeterParam) {
        String sql="delete  from hydropower_meter where id =? ";
        dbUtils.execSql(sql,hydropowerMeterParam.getId());
    }

    public void edit(HydropowerMeterParam hydropowerMeterParam) {
        String meterReadingDate = hydropowerMeterParam.getMeterReadingDate();
        DateTime parse = DateUtil.parse(meterReadingDate,"yyyy-MM-dd");
        List<HydropowerMeterParam> data = hydropowerMeterParam.getData();
        for (int i = 0; i < data.size(); i++) {
            HydropowerMeterParam hydropowerMeterParam1 = data.get(i);
            HouseBillParam houseBillParam=new HouseBillParam();
            houseBillParam.setId(hydropowerMeterParam1.getHouseBillId());
            HouseBill byId = houseBillService.getById(houseBillParam);
            Integer qsnum = byId.getQsnum();
            HydropowerMeter hydropowerMeter = this.queryHydropowerMeter(hydropowerMeterParam1);
            hydropowerMeter.setCost(hydropowerMeterParam1.getCost());
            hydropowerMeter.setDosage(hydropowerMeterParam1.getDosage());
            hydropowerMeter.setReading(hydropowerMeterParam1.getReading());
            hydropowerMeter.setMeterReadingDate(parse);
            String ss="填充到第"+qsnum+"期賬單";
            if (byId.getBillStatus()==3){
                ss="填充到清算賬單";
            }
            hydropowerMeter.setMeterStatus(ss);
            hydropowerMeter.setMeterFlag(1);
            hydropowerMeter.setUpdateTime(new Date());
            hydropowerMeter.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
            dbUtils.update(hydropowerMeter);
            HouseBillDetailParam houseBillDetailParam=new HouseBillDetailParam();
            houseBillDetailParam.setId(hydropowerMeter.getHouseBillDetailId());
            houseBillDetailParam.setAmount(hydropowerMeterParam1.getCost());
            houseBillDetailService.editJe(houseBillDetailParam);
        }
    }

    @Override
    public HydropowerMeter detail(HydropowerMeterParam hydropowerMeterParam) {
        return this.queryHydropowerMeter(hydropowerMeterParam);
    }

    /**
     * 获取水電抄表記錄表
     *
     * @author anti
     * @date 2021-05-10 21:19:36
     */
    private HydropowerMeter queryHydropowerMeter(HydropowerMeterParam hydropowerMeterParam) {
        HydropowerMeter hydropowerMeter = this.getById(hydropowerMeterParam);
        if (ObjectUtil.isNull(hydropowerMeter)) {
            throw new BusinessException(HydropowerMeterExceptionEnum.NOT_EXIST);
        }
        return hydropowerMeter;
    }


}
